<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './tableData';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import moment from 'moment';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    name: 'PostDrawer',
    components: { BasicDrawer, BasicForm },
    props: {
      type: {
        type: String,
        default: () => {
          return 'add';
        },
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);
      const userStore = useUserStore();
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });
      const formId = ref(null);
      const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formId.value = props.type === 'edit' ? data.record.id : null;
        if (unref(isUpdate)) {
          console.log(data);
          setFieldsValue({
            ...data.record,
            expireDate: moment(data.record.expireDate).format('x'),
            expireTime: moment(data.record.expireTime).format('x'),
          });
        } else {
          setFieldsValue({
            expireDate: moment(data.record).format('x'),
          });
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          let params = { ...values };
          params.expireDate = moment(Number(params.expireDate)).format('YYYY-MM-DD');
          params.userId = userStore.getUserInfo.user.id;
          params.expireTime = params.expireTime * 1;
          if (formId.value) {
            params.id = formId.value;
          }
          emit('success', params);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
